package cn.tedu.v4;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * 多人聊天室  Version 4
 */
public class Client {
    private static final String HOST = "127.0.0.1";
    private static final Integer PORT = 0202;
    private Socket socket;
    private String ip;
    private PrintWriter pw;
    private BufferedReader br;

    public Client() {
        try {
            socket = new Socket(HOST, PORT);
            ip = socket.getInetAddress().getHostAddress();
            br = new BufferedReader(new InputStreamReader(
                    socket.getInputStream(), "UTF8"));
            pw = new PrintWriter(new BufferedWriter(new
                    OutputStreamWriter(socket.getOutputStream
                    (), "UTF8")), true);
        } catch (SocketException e) {
            System.out.println("连接被重置或者断开");
        } catch (UnknownHostException e) {
            System.out.println("IP地址有问题，请询问服务器端！");
        } catch (IOException e) {
            System.out.println("客户端主动退出了：断开链接");
        }
    }

    public void start() {
        try {
            new Thread(() -> {
                try {
                    String message;
                    while ((message = br.readLine()) != null) {
                        System.out.println("服务器说：" + message);
                        System.out.print("客户端请输入：");
                    }
                } catch (IOException e) {
                    System.out.println("服务器端发来的消息断开了~");
                }
            }).start();

            Scanner input = new Scanner(System.in);
            while (true) {
                System.out.println("客户端请输入：");
                String sme = input.nextLine();
                pw.println(ip + "客户端说：" + sme);
            }

        } finally {
            if (pw != null)
                pw.close();
            if (br != null)
                try {
                    br.close();
                } catch (IOException e) {
                    System.out.println("服务器通讯内容失败~~");
                }
            if (socket != null && !socket.isClosed()) {
                System.out.println("客户端关闭成功！success~");
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("客户端关闭失败");
                }
            }
        }
    }

    public static void main(String[] args) {
        new Client().start();
    }
}
